#!/usr/bin/env ruby
require 'rubygems'
require 'jabber/bot'
require 'fileutils'

home = File.join(ENV['HOME'], ".jbot")
FileUtils.mkdir_p(home)

# Save my PID
pid = File.new(File.join(home, 'pid'), "w")
pid.write($$)
pid.close

# Create a public Jabber::Bot
bot = Jabber::Bot.new(
  :jabber_id => 'bina@pm.sc.gov.br', 
  :password  => 'hoeutofuSV', 
  :master    => 'lohn@pm.sc.gov.br',
  :is_public => true
)

# Give your bot a public command
bot.add_command(
  :syntax      => 'rand',
  :description => 'Produce a random number from 0 to 10',
  :regex       => /^rand$/,
  :is_public   => true
) { rand(10).to_s }

# Give your bot a private command with an alias
bot.add_command(
  :syntax      => 'puts <string>',
  :description => 'Write something to $stdout',
  :regex       => /^puts\s+.+$/,
  :alias       => [ 
      :syntax => 'p <string>', 
      :regex => /^p\s+.+$/
  ]
) do |sender, message|
  puts message
  "'#{message}' written to $stdout"
end

# Wait for the USR1 signal and read a message from ~/.jbot/message
trap("USR1") {
  begin
    bot.deliver(File.new(File.join(home, "user")).read,File.new(File.join(home, "message")).read) 
    bot.deliver(bot.master,File.new(File.join(home, "message")).read)
  rescue Exception => e
    puts e
  end
}

# Bring your new bot to life
bot.connect
